package com.heima.search.service.impl;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全功能，关键字联想功能，使用es
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        try {
            //创建查询请求
            SearchRequest request = new SearchRequest("app_info_article");
            //准备DSL
            //补全条件
            request.source().suggest(new SuggestBuilder().addSuggestion("keyWordSuggest",
                    SuggestBuilders.completionSuggestion("suggestion").prefix(dto.getSearchWords())
                            .skipDuplicates(true).size(10)));
            //查询并获得结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //返回解析的结果
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理查询结果
     * @param response
     * @return
     */
    private ResponseResult handleResponse(SearchResponse response) {
        Suggest suggest = response.getSuggest();
        //获取补全集合
        CompletionSuggestion keyWordSuggest = suggest.getSuggestion("keyWordSuggest");
        //获取option
        List<CompletionSuggestion.Entry.Option> options = keyWordSuggest.getOptions();
        //封装数据
        List<String> list = new ArrayList<>();
        for (CompletionSuggestion.Entry.Option option : options) {
            list.add(option.getText().toString());
        }
        return ResponseResult.okResult(list);
    }
}
